package org.example.rowing.controller;

import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.control.DatePicker;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
import lombok.extern.slf4j.Slf4j;
import org.example.rowing.domain.Event;
import org.example.rowing.enums.BoatTypeEnum;
import org.example.rowing.service.EventInfoService;
import org.example.rowing.vo.EventVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;

import java.time.LocalDate;

@Controller
@Slf4j
public class UpdateEventController {
    @FXML
    private TextField eventNameField;

    @FXML
    private DatePicker startDateField;

    @FXML
    private DatePicker endDateField;

    @FXML
    private TextField locationField;

    @FXML
    private Label popupTitle;

    private EventVO eventToEdit;

    @Autowired
    private EventInfoService eventInfoService;

    // 用于在弹出框初始化时设置事件信息（用于编辑）
    public void initialize(EventVO eventVO) {
        if (eventVO != null) {
            this.eventToEdit = eventVO;
            popupTitle.setText("修改赛事");
            eventNameField.setText(eventVO.getName());
            startDateField.setValue(LocalDate.parse(eventVO.getStartDate()));
            endDateField.setValue(LocalDate.parse(eventVO.getEndDate()));
            locationField.setText(eventVO.getLocation());
        } else {
            popupTitle.setText("添加赛事");
            this.eventToEdit = null;
        }
    }

    // 保存赛事
    @FXML
    private void handleSaveEvent() {
        String eventName = eventNameField.getText();
        LocalDate startDate = startDateField.getValue();
        LocalDate endDate = endDateField.getValue();
        String location = locationField.getText();

        if (eventName.isEmpty() || startDate == null || endDate == null || location.isEmpty()) {
            log.warn("请填写完整的赛事信息");
            showErrorDialog("请填写完整的赛事信息");
            return;
        }

        Event event = new Event(null, eventName, startDate.toString(), endDate.toString(), location, BoatTypeEnum.ROWING);

        if (eventToEdit == null) {
            log.info("添加新赛事: {}", event);
        } else {
            event.setId(eventToEdit.getId());
            log.info("修改赛事: {}", event);
        }
        eventInfoService.saveOrUpdateEvent(event);

        // 关闭弹窗
        closeWindow();
    }

    // 取消操作，关闭弹出框
    @FXML
    private void handleCancel() {
        closeWindow();
    }

    private void closeWindow() {
        Stage stage = (Stage) eventNameField.getScene().getWindow();
        stage.close();
    }

    // 弹出错误提示框
    private void showErrorDialog(String message) {
        Alert alert = new Alert(Alert.AlertType.ERROR);
        alert.setTitle("输入错误");
        alert.setHeaderText(null);
        alert.setContentText(message);
        alert.showAndWait();
    }
}
